﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using nwrole.lib;

namespace nwrole.lib2 {
    public class PluginBase {
        protected PluginData PluginData { get; set; }
        
        protected Thread Thread { get; set; }
        protected TimeSpan DelayStart { get; set; }
        protected List<PluginError> Errors = new List<PluginError>();
        protected bool Running { get; private set; }

        public PluginBase() { }

        public void Initialize(PluginData pluginData) {
            PluginData = pluginData;
            DelayStart = TimeSpan.FromSeconds(0);

            this.OnInit();
        }

        public void Start() {
            if (Thread != null && Thread.IsAlive)
                return;

            Running = true;
            Thread = new Thread(new ThreadStart(this.CoreStart));
            Thread.Start();
        }

        protected virtual void CoreStart() {
            Thread.Sleep(DelayStart);
            this.OnStart();
            this.Execute();
        }

        public void Stop() {
            if (Thread == null || !Thread.IsAlive)
                return;

            Running = false;
            Thread.Join(TimeSpan.FromSeconds(10));
            Thread = null;

            this.CoreStop();
        }

        protected virtual void CoreStop() {
            this.OnStop();
        }

        protected virtual void OnInit() { }
        protected virtual void OnStart() { }
        protected virtual void OnStop() { }
        protected virtual void Execute() { }

        protected void RegisterError(string origin, string message) {
            Errors.Add(new PluginError(origin, message));
        }

        protected void RegisterError(string origin, string message, Exception exception) {
            Errors.Add(new PluginError(origin, message, exception));
        }
    }
}
